package com.yunmaozj.tools.site.server.config;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

import static java.util.Objects.isNull;

/**
 * @author zhongminghong
 * @email zhongmh@yunmaozj.com
 * @create 2022-05-28 23:32
 */
@Slf4j
@Component
@AllArgsConstructor
public class ResourceCacheManager {

    private StringRedisTemplate redisTemplate;

    public void addResource(String username, String... projectIds) {
        if (StringUtils.isEmpty(username) || isNull(projectIds) || projectIds.length == 0) {
            return;
        }
        redisTemplate.opsForSet().add("_site_server_" + username, projectIds);
        redisTemplate.expire("_site_server_" + username, 30, TimeUnit.MINUTES);
    }

    /**
     * 判断当前用户是否有项目的权限
     *
     * @param username
     * @param projectId
     * @return
     */
    public boolean exists(String username, String projectId) {
        return redisTemplate.opsForSet().isMember("_site_server_" + username, projectId);
    }

    public boolean isLogin(String sessionId) {
        return redisTemplate.hasKey(sessionId);
    }

    public String username(String sessionId) {
        return redisTemplate.opsForValue().get(sessionId);
    }

    public void addLoginInfo(String sessionId, String username) {
        redisTemplate.opsForValue().set(sessionId, username, 30, TimeUnit.MINUTES);
    }
}
